package com.controller;

import com.event.NotificationEvent;
import com.pojo.ChatMessage;
import com.pojo.Notifications;
import com.pojo.Result;
import com.service.ChatService;
import com.service.NotificationsService;
import com.vo.ChatMessageVO;
import com.vo.NotificationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;
import java.util.Map;

@Controller
@RestController
@RequestMapping("/api/chat")
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private ChatService chatService;

    @Autowired
    private NotificationsService notificationService;

    // ------------------- 聊天功能（WebSocket） -------------------
    @MessageMapping("/chat/send")
    public void sendChatMessage(ChatMessage message, Principal principal) {
        ChatMessageVO savedMessage = chatService.saveChatMessage(message);
        messagingTemplate.convertAndSend("/chat/" + message.getReceiverId(), savedMessage);
    }

    @MessageMapping("/chat/read")
    public void markAsRead(Integer messageId, Principal principal) {
        Integer userId = Integer.parseInt(principal.getName());
        chatService.markMessageAsRead(messageId, userId);
    }

    // ------------------- 通知功能（WebSocket） -------------------
    @MessageMapping("/notification/read")
    public void markNotificationAsRead(Integer notificationId, Principal principal) {
        notificationService.markNotificationAsRead(notificationId);
    }

    // ------------------- HTTP 接口 -------------------
    @GetMapping("/history")
    public Result<List<ChatMessageVO>> getChatHistory(
            @RequestParam Integer otherUserId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            Principal principal) {
        Integer userId = Integer.parseInt(principal.getName());
        return (Result<List<ChatMessageVO>>) chatService.getChatHistory(userId, otherUserId, page, size);
    }

    @GetMapping("/unread/count")
    public Result<Integer> getUnreadCount(Principal principal) {
        Integer userId = Integer.parseInt(principal.getName());
        return Result.success(chatService.countUnreadMessages(userId));
    }

    @PostMapping("/notification/read")
    public Result<Void> markNotificationAsReadHttp(@RequestBody Map<String, Integer> payload) {
        notificationService.markNotificationAsRead(payload.get("notificationId"));
        return Result.success();
    }

    // ------------------- 事件监听推送 -------------------
    @Async // 异步推送，不阻塞业务
    @EventListener
    public void handleNotificationEvent(NotificationEvent event) {
        Notifications notification = event.getNotification();
        NotificationVO vo = notificationService.getNotificationVO(notification).getData();
        messagingTemplate.convertAndSendToUser(
                notification.getUserId().toString(),
                "/notifications",
                vo
        );
    }
}